package com.yiren.manager.ctrl.elder;

import java.beans.IntrospectionException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.StringUtil;
import com.yiren.core.exception.MyException;
import com.yiren.core.exception.SwallowException;
import com.yiren.core.repository.utils.QueryResult;
import com.yiren.core.utils.FavoriteSet;
import com.yiren.core.utils.HTTPResult;
import com.yiren.core.utils.JsonMapperTool;
import com.yiren.core.utils.UUIDGenerator;
import com.yiren.entity.YrBaseServiceCost;
import com.yiren.entity.YrBed;
import com.yiren.entity.YrBedCost;
import com.yiren.entity.YrCaregiver;
import com.yiren.entity.YrCgIndiServiceSendOrder;
import com.yiren.entity.YrCgSendOrder;
import com.yiren.entity.YrElder;
import com.yiren.entity.YrElderArrearage;
import com.yiren.entity.YrElderBeHospital;
import com.yiren.entity.YrElderBedRecord;
import com.yiren.entity.YrElderPayRecord;
import com.yiren.entity.YrElderWallet;
import com.yiren.entity.YrMealCard;
import com.yiren.entity.YrNursingCost;
import com.yiren.entity.YrRoom;
import com.yiren.entity.YrStaffInfo;
import com.yiren.entity.YrSubjectRoom;
import com.yiren.entity.YrUserVipCard;
import com.yiren.entity.YrUserVipCardRecord;
import com.yiren.entity.YrUserVipCardRent;
import com.yiren.manager.form.department.YrCaregiverForm;
import com.yiren.manager.form.department.YrCgIndiServiceSendOrderForm;
import com.yiren.manager.form.department.YrCgSendOrderForm;
import com.yiren.manager.form.elder.YrElderBeHospitalForm;
import com.yiren.manager.form.elder.YrElderForm;
import com.yiren.manager.form.elder.YrElderWalletForm;
import com.yiren.manager.form.pension.YrBaseServiceCostForm;
import com.yiren.manager.form.pension.YrBedCostForm;
import com.yiren.manager.form.pension.YrNursingCostForm;
import com.yiren.manager.form.vip.YrUserVipCardForm;
import com.yiren.manager.form.vip.YrUserVipCardRecordForm;
import com.yiren.manager.form.vip.YrUserVipCardRentForm;
import com.yiren.manager.service.iface.beds.YrBedService;
import com.yiren.manager.service.iface.beds.YrRoomService;
import com.yiren.manager.service.iface.department.YrCaregiverService;
import com.yiren.manager.service.iface.department.YrCgIndiServiceSendOrderService;
import com.yiren.manager.service.iface.department.YrCgSendOrderService;
import com.yiren.manager.service.iface.department.YrStaffInfoService;
import com.yiren.manager.service.iface.department.YrSubjectRoomService;
import com.yiren.manager.service.iface.elder.YrElderBeHospitalService;
import com.yiren.manager.service.iface.elder.YrElderService;
import com.yiren.manager.service.iface.elder.YrElderWalletService;
import com.yiren.manager.service.iface.messhall.YrMealCardService;
import com.yiren.manager.service.iface.pension.YrBaseServiceCostService;
import com.yiren.manager.service.iface.pension.YrBedCostService;
import com.yiren.manager.service.iface.pension.YrNursingCostService;
import com.yiren.manager.service.iface.vip.YrUserVipCardRecordService;
import com.yiren.manager.service.iface.vip.YrUserVipCardRentService;
import com.yiren.manager.service.iface.vip.YrUserVipCardService;
import com.yiren.manager.task.DateUtil;
import com.yiren.manager.utils.ObjectUtils;

@Controller
@RequestMapping("/elderBeHospital")
public class YrElderBeHospitalController extends YrElderBaseController<YrElderBeHospitalForm, YrElderBeHospital> {

	@Autowired
	private YrElderBeHospitalService selfService;

	@Autowired
	private YrBedService bedService;

	@Autowired
	private YrUserVipCardService userVipCardService;

	@Autowired
	private YrElderService elderService;

	@Autowired
	private YrCgIndiServiceSendOrderService cgIndiServiceSendOrderService;

	@Autowired
	private YrCgSendOrderService cgSendOrderService;

	@Autowired
	private YrCaregiverService caregiverService;

	@Autowired
	private YrElderWalletService elderWalletService;

	@Autowired
	private YrBaseServiceCostService baseServiceCostService;

	@Autowired
	private YrNursingCostService nursingCostService;

	@Autowired
	private YrUserVipCardRecordService userVipCardRecordService;

	@Autowired
	private YrUserVipCardRentService userVipCardRentService;

	@Autowired
	private YrStaffInfoService staffInfoService;

	@Autowired
	private YrMealCardService mealCardService;
	
	@Autowired
	private YrRoomService roomService;
	
	@Autowired
	private YrBedCostService bedCostService;
	
	@Autowired
	private YrSubjectRoomService subjectRoomService;

	// 保存实体
	@RequestMapping("/save")
	@ResponseBody
	public HTTPResult<YrElderBeHospitalForm> save(String data)
			throws SwallowException, MyException, InstantiationException, IllegalAccessException,
			IllegalArgumentException, InvocationTargetException, IntrospectionException {
		HTTPResult<YrElderBeHospitalForm> result = new HTTPResult<YrElderBeHospitalForm>();
		JsonMapperTool tool = new JsonMapperTool(data);
		YrElderBeHospitalForm form = tool.mapper("elderBeHospital", YrElderBeHospitalForm.class);
		if (null == form) {
			throwExp("param.error");
		}
		YrElder elder = elderService.findOne(form.getElderId());
		if (null == elder) {
			throwExp("查询不到相应的老者");
		}
		if (elder.getElderType() == 2) {// 如果是院外老人
			throwExp("该老者为院外老者，不能办理入院");
		}
		String sqlWhere = "elder_id=?1 AND be_status<>2";

		QueryResult<YrElderBeHospital> qrElderBeHospital = selfService.find(YrElderBeHospital.class, sqlWhere,
				new Object[] { form.getElderId() });
		if (qrElderBeHospital.getTotalRecord() > 0) {
			throwExp("该老者已办理过入院登记手续，请勿重复办理");
		}
		if(form.getHouseTypeType()==1){//如果是vip卡户型
			if(form.getUserVipCardId()==null){
				throwExp("请绑定用户vip卡");
			}
			YrUserVipCard userVipCard = userVipCardService.findOne(form.getUserVipCardId());
			if(null==userVipCard){
				throwExp("查询不到相关的用户vip信息");
			}
		}
		Date date = new Date();
		boolean isNew = false;
		List<YrBed> beds = new ArrayList<YrBed>();
		YrElderBedRecord bedRecord = null;
		form.setUpdateTime(date);
		if (null == form.getBeHospitalId() || form.getBeHospitalId().isEmpty()) {
			// 新入住
			form.setBeHospitalId(UUIDGenerator.getUUID());
			form.setCreateTime(date);
			form.setBeType(0);
			form.setBeStatus(0);
			form.setBedStatus(0);
			form.setBeDate(form.getCreateTime());
			form.setPrePayDate(date);
			form.setBeNumber(getBeNumber());

			isNew = true;
			// 插入入住记录
			bedRecord = ObjectUtils.objectToObject(form, YrElderBedRecord.class);
			bedRecord.setHandleStatus(0);
		}
		YrElderBeHospital entity = ObjectUtils.objectToObject(form, YrElderBeHospital.class);
		YrUserVipCard userVipCard = null;
		if (StringUtil.isEmpty(form.getElderId())) {
			throwExp("缺少参数：elderId");
		}
		
		YrElderWallet elderWallet = null;
		YrMealCard mealCard = null;

		if (isNew) {// 如果是新入住
			if (StringUtil.isEmpty(form.getBaseServiceCostId())) {
				throwExp("缺少参数:baseServiceCostId");
			}
			YrBaseServiceCost baseServiceCost = baseServiceCostService.findOne(form.getBaseServiceCostId());
			if (null == baseServiceCost) {
				throwExp("找不到对应的基础服务费数据");
			}
			if (StringUtil.isEmpty(form.getNursingCostId())) {
				throwExp("缺少参数:nursingCostId");
			}
			YrNursingCost nursingCost = nursingCostService.findOne(form.getNursingCostId());
			if (null == nursingCost) {
				throwExp("找不到对应的护理费数据");
			}
			sqlWhere = "elder_id=?1";
			QueryResult<YrElderWallet> qrElderWallet = elderWalletService.find(YrElderWallet.class, sqlWhere,
					new Object[] { form.getElderId() });
			if (qrElderWallet.getResultList().isEmpty()) {// 如果该老者没有钱包
				// 新增一个钱包
				elderWallet = new YrElderWallet();
				elderWallet.setElderWalletId(UUIDGenerator.getUUID());
				elderWallet.setElderId(elder.getElderId());
				elderWallet.setElderName(elder.getName());
				elderWallet.setElderCardId(elder.getCardId());
				elderWallet.setWalletBalance(Float.valueOf(0));
				elderWallet.setRemindStatus(0);
				elderWallet.setCreateId(form.getCreateId());
				elderWallet.setCreateTime(date);
			}
			sqlWhere = "card_person_id=?1";
			QueryResult<YrMealCard> qrMealCard = mealCardService.find(YrMealCard.class, sqlWhere,
					new Object[] { form.getElderId() });
			if (qrMealCard.getResultList().isEmpty()) {// 如果该老者没有饭卡
				// 新增一张饭卡
				mealCard = new YrMealCard();
				mealCard.setMealCardId(UUIDGenerator.getUUID());
				mealCard.setCardPersonId(elder.getElderId());
				mealCard.setCardPersonName(elder.getName());
				mealCard.setCardCardId(elder.getCardId());
				mealCard.setBalance(Float.valueOf(0));
				mealCard.setCardType(0);
				mealCard.setCreateTime(date);
				mealCard.setCreateId(form.getCreateId());
				mealCard.setPersonType(1);
			}
		}

		if (StringUtil.isEmpty(entity.getBedId())) {
			throwExp("缺少参数:bedId");
		}
		YrBed bed = bedService.findOne(entity.getBedId());
		if (bed == null) {
			throwExp("查询不到床位");
		}
		entity.setBuildingId(bed.getBuildingId());
		entity.setBuildingName(bed.getBuildingName());
		entity.setFloorId(bed.getFloorId());
		entity.setFloorName(bed.getFloorName());
		entity.setRoomId(bed.getRoomId());
		entity.setBedNumber(bed.getBedNumber());
		YrRoom room = roomService.findOne(form.getRoomId());
		if(null!=room){
			form.setRoomNumber(entity.getRoomNumber());
			form.setRoomType(entity.getRoomType());
		}
		elder.setBeHospitalStatus(1);// 修改为住院状态
		bed.setUseStatus(1);// 改为使用状态
		beds.add(bed);

		FavoriteSet favoriteSet = new FavoriteSet();
		favoriteSet.putFavorite("elderBeHospital", entity);
		favoriteSet.putFavorite("bedList", beds);
		favoriteSet.putFavorite("userVipCard", userVipCard);
		favoriteSet.putFavorite("elder", elder);
		favoriteSet.putFavorite("bedRecord", bedRecord);
		favoriteSet.putFavorite("elderWallet", elderWallet);
		favoriteSet.putFavorite("mealCard", mealCard);

		selfService.addByFavoriteSet(favoriteSet);

		List<YrElderBeHospitalForm> formList = new ArrayList<YrElderBeHospitalForm>();
		formList.add(form);
		result.setData(formList);

		return result;
	}

	@RequestMapping("update")
	@ResponseBody
	public HTTPResult<YrElderBeHospitalForm> update(String data) throws SwallowException, MyException,
			InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		HTTPResult<YrElderBeHospitalForm> result = new HTTPResult<YrElderBeHospitalForm>();
		JsonMapperTool tool = new JsonMapperTool(data);
		YrElderBeHospitalForm form = tool.mapper("elderBeHospital", YrElderBeHospitalForm.class);
		if (null == form) {
			throwExp("param.error");
		}

		form.setUpdateTime(new Date());

		form = turnRoom(form,false);

		List<YrElderBeHospitalForm> formList = new ArrayList<YrElderBeHospitalForm>();
		formList.add(form);

		result.setData(formList);
		return result;
	}

	@RequestMapping("test")
	@ResponseBody
	public HTTPResult<YrElderBeHospitalForm> test() {
		HTTPResult<YrElderBeHospitalForm> result = new HTTPResult<YrElderBeHospitalForm>();

		String beNumber = selfService.findByJPQL("SELECT max(beNumber) as beNumber");

		System.out.println("beNumber=" + getBeNumber());

		return result;
	}

	private String getBeNumber() {
		String beNumber = selfService.findByJPQL("SELECT max(beNumber) as beNumber");
		if (StringUtil.isEmpty(beNumber)) {
			return "000000001";
		}
		Integer codeNum = Integer.parseInt(beNumber) + 1;
		String codeStr = codeNum.toString();
		StringBuilder tempStr = new StringBuilder();
		for (int i = 0; i < 9 - codeStr.length(); i++) {
			tempStr.append("0");
		}
		tempStr.append(codeStr);
		return tempStr.toString();
	}

	@RequestMapping("turnRoom")
	@ResponseBody
	public HTTPResult<YrElderBeHospitalForm> turnRoom(String data) throws SwallowException, MyException,
			InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		HTTPResult<YrElderBeHospitalForm> result = new HTTPResult<YrElderBeHospitalForm>();
		JsonMapperTool tool = new JsonMapperTool(data);
		YrElderBeHospitalForm form = tool.mapper("elderBeHospital", YrElderBeHospitalForm.class);
		form = turnRoom(form,true);
		List<YrElderBeHospitalForm> formList = new ArrayList<YrElderBeHospitalForm>();
		form.setSysTime(new Date());
		formList.add(form);
		result.setData(formList);

		return result;
	}

	public YrElderBeHospitalForm turnRoom(YrElderBeHospitalForm form,boolean isTurnRoom) throws MyException, InstantiationException, IllegalAccessException,
			IllegalArgumentException, InvocationTargetException {
		if (null == form) {
			throwExp("param.error");
		}
		YrElderBeHospital elderBeHospital = selfService.findOne(form.getBeHospitalId());
		if (null == elderBeHospital) {
			throwExp("查询不到相关入住信息");
		}
		if (StringUtil.isEmpty(form.getElderId())) {
			throwExp("缺少参数：elderId");
		}
		YrElder elder = elderService.findOne(form.getElderId());
		if (null == elder) {
			throwExp("查询不到相应的老者");
		}
		if (StringUtil.isEmpty(form.getBaseServiceCostId())) {
			throwExp("缺少参数:baseServiceCostId");
		}
		YrBaseServiceCost baseServiceCost = baseServiceCostService.findOne(form.getBaseServiceCostId());
		if (null == baseServiceCost) {
			throwExp("找不到对应的基础服务费数据");
			
		}
		if (StringUtil.isEmpty(form.getNursingCostId())) {
			throwExp("缺少参数:nursingCostId");
		}
		YrNursingCost nursingCost = nursingCostService.findOne(form.getNursingCostId());
		if (null == nursingCost) {
			throwExp("找不到对应的护理费数据");
		}
		// 是否需求重新计费（如果转换科室，需要重新计费）
		boolean costFlag = elderBeHospital.getSubjectRoomId() == form.getSubjectRoomId();

		List<YrBed> beds = new ArrayList<YrBed>();
		YrElderBedRecord bedRecord = null;

		if(isTurnRoom){
			YrBed bed = bedService.findOne(elderBeHospital.getBedId());
			if (null == bed) {
				throwExp("找不到该老者原来的床位");
			}
			if (!bed.getBedId().equals(form.getBedId())) { // 转房
				bed.setUseStatus(0);// 将原来的 设置为未使用状态
				form.setBeType(1);// 设置为转房
				beds.add(bed);
				// 插入转房记录
				bedRecord = ObjectUtils.objectToObject(form, YrElderBedRecord.class);
				bedRecord.setHandleStatus(0);
			} else {
				throwExp("请选择转入的房间");
			}
			if (StringUtil.isEmpty(form.getBedId())) {
				throwExp("缺少参数:bedId");
			}
			YrBed bedNew = bedService.findOne(form.getBedId());
			if (bedNew == null) {
				throwExp("查询不到床位");
			}
			form.setBuildingId(bedNew.getBuildingId());
			form.setBuildingName(bedNew.getBuildingName());
			form.setFloorId(bedNew.getFloorId());
			form.setFloorName(bedNew.getFloorName());
			form.setRoomId(bedNew.getRoomId());
			form.setBedNumber(bedNew.getBedNumber());
			YrRoom room = roomService.findOne(form.getRoomId());
			if(null!=room){
				form.setRoomNumber(room.getRoomNumber());
				form.setRoomType(room.getRoomType());
			}
			bedNew.setUseStatus(1);
			beds.add(bedNew);
		}

		List<YrElderPayRecord> elderPayRecords = new ArrayList<YrElderPayRecord>();// 缴费记录列表
		List<YrElderArrearage> elderArrearages = new ArrayList<YrElderArrearage>();// 欠费记录列表

		Date now = new Date();
		YrElderWallet elderWallet = null;

		if (costFlag) {// 需要重新计费
			YrSubjectRoom subjectRoom = subjectRoomService.findOne(form.getSubjectRoomId());
			if(null==subjectRoom){
				throwExp("找不到所转入的科室信息");
			}
			
			form.setSubjectRoomName(subjectRoom.getRoomName());
			
			int payDays = DateUtil.daysOfTwo(now, elderBeHospital.getPrePayDate());
			Float payMoney = Float.valueOf(0);
			String sqlWhere = "elder_id=?1";
			QueryResult<YrElderWallet> qrElderWallet = elderWalletService.find(YrElderWallet.class, sqlWhere,
					new Object[] { elder.getElderId() });
			elderWallet = qrElderWallet.getResultList().get(0);
			YrElderPayRecord elderPayRecord = null;
			if (elderBeHospital.getHouseTypeType() == 2) {// 不是vip卡入住 扣取床位费
				payMoney = elderBeHospital.getBedCostPrice() / 15 * payDays;
//				if (elderWallet.getWalletBalance() - payMoney < 0) {
//					// 增加一条欠费记录
//					YrElderArrearage elderArrearage = constElderArreagrage(elderBeHospital.getBeHospitalId(),elder, 4, elderBeHospital.getBeHospitalId(),
//							payMoney, "钱包余额不足", "床位费", form.getCreateId());
//					elderArrearages.add(elderArrearage);
//				} else {
					// 钱包余额充足，增加一条缴费记录
					elderPayRecord = costElderPayRecord(elderBeHospital.getBeHospitalId(),"床位费", elder, 4, elderBeHospital.getBeHospitalId(), payMoney,
							2,0,form.getCreateId(),1);
					elderPayRecords.add(elderPayRecord);
					elderWallet.setWalletBalance(elderWallet.getWalletBalance() - payMoney);
//				}
			}

			payMoney = baseServiceCost.getPrice() / 15 * payDays;
//			if (elderWallet.getWalletBalance() - payMoney < 0) {
//				// 增加一条欠费记录
//				YrElderArrearage elderArrearage = constElderArreagrage(elderBeHospital.getBeHospitalId(),elder, 1, elderBeHospital.getBeHospitalId(),
//						payMoney, "钱包余额不足", "基础服务费", form.getCreateId());
//				elderArrearages.add(elderArrearage);
//			} else {
				// 增加一条缴费记录
				elderPayRecord = costElderPayRecord(elderBeHospital.getBeHospitalId(),"基础服务费", elder, 1, elderBeHospital.getBeHospitalId(), payMoney, 2,0,form.getCreateId(),1);
				elderPayRecords.add(elderPayRecord);
				elderWallet.setWalletBalance(elderWallet.getWalletBalance() - payMoney);
//			}

			payMoney = nursingCost.getPrice() / 15 * payDays;
//			if (elderWallet.getWalletBalance() - payMoney < 0) {
//				// 增加一条欠费记录
//				YrElderArrearage elderArrearage = constElderArreagrage(elderBeHospital.getBeHospitalId(),elder, 2, elderBeHospital.getBeHospitalId(),
//						payMoney, "钱包余额不足", "护理费", form.getCreateId());
//				elderArrearages.add(elderArrearage);
//			} else {
				// 增加一条缴费记录
				elderPayRecord = costElderPayRecord(elderBeHospital.getBeHospitalId(),"护理费", elder, 2, elderBeHospital.getBeHospitalId(), payMoney, 2,0,form.getCreateId(),1);
				elderPayRecords.add(elderPayRecord);
				elderWallet.setWalletBalance(elderWallet.getWalletBalance() - payMoney);
//			}
			elderBeHospital.setPrePayDate(now);
			
		}

		FavoriteSet favoriteSet = new FavoriteSet();
		favoriteSet.putFavorite("elderBeHospital", ObjectUtils.objectToObjectWithOutNull(form, elderBeHospital));
		favoriteSet.putFavorite("bedList", beds);
		// favoriteSet.putFavorite("elder",elder);
		favoriteSet.putFavorite("bedRecord", bedRecord);
		favoriteSet.putFavorite("elderPayRecords", elderPayRecords);
		favoriteSet.putFavorite("elderArrearages", elderArrearages);
		favoriteSet.putFavorite("elderWallet", elderWallet);

		selfService.executeTurnRoomFavorites(favoriteSet);
		
		return ObjectUtils.objectToObject(elderBeHospital, YrElderBeHospitalForm.class);
	}

	/**
	 * 根据楼层查询老者床位信息
	 * 
	 * @param floorId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("findByFloorId")
	@ResponseBody
	public HTTPResult<YrElderBeHospitalForm> findByFloorId(String floorId) throws Exception {
		HTTPResult<YrElderBeHospitalForm> result = new HTTPResult<YrElderBeHospitalForm>();
		String sqlWhere = "floor_id = ?1 AND be_status<>2";
		LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
		map.put("bedNumber", "ASC");
		map.put("floorName", "ASC");
		map.put("roomId", "ASC");
		QueryResult<YrElderBeHospital> qrElderHospital = selfService.find(YrElderBeHospital.class, sqlWhere,
				new Object[] { floorId }, map); 

		List<YrElderBeHospitalForm> formList = new ArrayList<YrElderBeHospitalForm>();
		for (YrElderBeHospital entity : qrElderHospital.getResultList()) {
			YrElderBeHospitalForm form = toForm(entity);
			YrElder elder = elderService.findOne(form.getElderId());
			if (null != elder) {
				form.setElderForm(ObjectUtils.objectToObject(elder, YrElderForm.class));
			}
			YrBed bed = bedService.findOne(entity.getBedId());
			if(null!=bed){
				form.setBedNumber(bed.getBedNumber());
			}
			formList.add(form);
		}

		result.setData(formList);

		return result;
	}
	
	@RequestMapping("findHistory")
	@ResponseBody
	public HTTPResult<YrElderBeHospitalForm> findHistory(String searchVal) throws Exception {
		HTTPResult<YrElderBeHospitalForm> result = new HTTPResult<YrElderBeHospitalForm>();
		
		String sqlWhere = "card_id=?1 OR name=?2 AND elder_type=1";
			
		QueryResult<YrElder> qrElder = elderService.find(YrElder.class, sqlWhere, new Object[]{searchVal,searchVal});
		sqlWhere = "elder_id=?1 AND be_status=2";
		LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
		map.put("createTime", "desc");
		List<YrElderBeHospitalForm> formList = new ArrayList<YrElderBeHospitalForm>();
		for(YrElder elder : qrElder.getResultList()){
			QueryResult<YrElderBeHospital> qrElderHospital = selfService.find(YrElderBeHospital.class, sqlWhere,
					new Object[] { elder.getElderId() }, map);
			for (YrElderBeHospital entity : qrElderHospital.getResultList()) {
				YrElderBeHospitalForm form = toForm(entity);
				if (null != elder) {
					form.setElderForm(ObjectUtils.objectToObject(elder, YrElderForm.class));
				}
				formList.add(form);
			}
		}
		result.setData(formList);
		return result;
	}
	
	@RequestMapping("findBeStatus")
	@ResponseBody
	public HTTPResult<YrElderBeHospitalForm> findBeStatus(String searchVal) throws Exception {
		HTTPResult<YrElderBeHospitalForm> result = new HTTPResult<YrElderBeHospitalForm>();
		
		String sqlWhere = "card_id=?1 OR name=?2 AND elder_type=1";
		
		QueryResult<YrElder> qrElder = elderService.find(YrElder.class, sqlWhere, new Object[]{searchVal,searchVal});
		sqlWhere = "elder_id=?1 AND be_status<>2";
		LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
		map.put("createTime", "desc");
		List<YrElderBeHospitalForm> formList = new ArrayList<YrElderBeHospitalForm>();
		for(YrElder elder : qrElder.getResultList()){
			QueryResult<YrElderBeHospital> qrElderHospital = selfService.find(YrElderBeHospital.class, sqlWhere,
					new Object[] { elder.getElderId() }, map);
			for (YrElderBeHospital entity : qrElderHospital.getResultList()) {
				YrElderBeHospitalForm form = toForm(entity);
				if (null != elder) {
					form.setElderForm(ObjectUtils.objectToObject(elder, YrElderForm.class));
				}
				formList.add(form);
			}
		}
		result.setData(formList);
		return result;
	}
	
	@RequestMapping("findByElderId")
	@ResponseBody
	public HTTPResult<YrElderBeHospitalForm> findByElderId(String elderId) throws Exception {
		HTTPResult<YrElderBeHospitalForm> result = new HTTPResult<YrElderBeHospitalForm>();

		String sqlWhere = "elder_id=?1 AND be_status<>2";
		QueryResult<YrElderBeHospital> qrElderBeHospital = selfService.find(YrElderBeHospital.class, sqlWhere,
				new Object[] { elderId });
		List<YrElderBeHospitalForm> formList = new ArrayList<>();
		for (YrElderBeHospital entity : qrElderBeHospital.getResultList()) {
			formList.add(toForm(entity));
		}
		result.setData(formList);
		return result;
	}

	@RequestMapping("findOne")
	@ResponseBody
	public HTTPResult<YrElderBeHospitalForm> findOne(String id) throws Exception {
		HTTPResult<YrElderBeHospitalForm> result = new HTTPResult<YrElderBeHospitalForm>();
		YrElderBeHospital entity = selfService.findOne(id);
		if (null == entity) {
			throwExp("查询不到相关住院登记信息");
		}
		YrElderBeHospitalForm form = toForm(entity);
		YrElder elder = elderService.findOne(form.getElderId());
		if (null != elder) {
			form.setElderForm(ObjectUtils.objectToObject(elder, YrElderForm.class));
		}
		String sqlWhere = "elder_id=?1";
		QueryResult<YrElderWallet> qrElderWallet = elderWalletService.find(YrElderWallet.class, sqlWhere,
				new Object[] { entity.getElderId() });
		if (qrElderWallet.getTotalRecord() > 0) {
			form.setElderWalletForm(
					ObjectUtils.objectToObject(qrElderWallet.getResultList().get(0), YrElderWalletForm.class));
		}
		if (entity.getHouseTypeType() == 1) {// 如果是vip卡入住户型
			YrUserVipCard userVipCard = userVipCardService.findOne(form.getUserVipCardId());
			if (null != userVipCard) {
				form.setUserVipCardForm(ObjectUtils.objectToObject(userVipCard, YrUserVipCardForm.class));
			}
		}

		List<YrElderBeHospitalForm> formList = new ArrayList<YrElderBeHospitalForm>();
		formList.add(form);

		result.setData(formList);
		return result;

	}
	
	@RequestMapping("findDetail")
	@ResponseBody
	public HTTPResult<YrElderBeHospitalForm> findDetail(String id) throws Exception {
		HTTPResult<YrElderBeHospitalForm> result = new HTTPResult<YrElderBeHospitalForm>();
		YrElderBeHospital entity = selfService.findOne(id);
		if (null == entity) {
			throwExp("查询不到相关入院登记信息");
		}
		YrElderBeHospitalForm form = toForm(entity);
		YrElder elder = elderService.findOne(form.getElderId());
		if (null != elder) {
			form.setElderForm(ObjectUtils.objectToObject(elder, YrElderForm.class));
		}
		String sqlWhere = "elder_id=?1";
		QueryResult<YrElderWallet> qrElderWallet = elderWalletService.find(YrElderWallet.class, sqlWhere,
				new Object[] { entity.getElderId() });
		if (qrElderWallet.getTotalRecord() > 0) {
			form.setElderWalletForm(
					ObjectUtils.objectToObject(qrElderWallet.getResultList().get(0), YrElderWalletForm.class));
		}
		if (entity.getHouseTypeType() == 1) {// 如果是vip卡入住户型
			YrUserVipCard userVipCard = userVipCardService.findOne(form.getUserVipCardId());
			if (null != userVipCard) {
				form.setUserVipCardForm(ObjectUtils.objectToObject(userVipCard, YrUserVipCardForm.class));
				sqlWhere = "user_vip_card_id=?1";
				QueryResult<YrUserVipCardRecord> qrUserVipCardRecord = userVipCardRecordService.find(
						YrUserVipCardRecord.class, sqlWhere,
						new Object[] { form.getUserVipCardForm().getUserVipCardId() });
				if (qrUserVipCardRecord.getTotalRecord() > 0) {
					form.setUserVipCardRecordForm(ObjectUtils.objectToObject(qrUserVipCardRecord.getResultList().get(0),
							YrUserVipCardRecordForm.class));
				}
				QueryResult<YrUserVipCardRent> qrUserVipCardRent = userVipCardRentService.find(YrUserVipCardRent.class,
						sqlWhere, new Object[] { form.getUserVipCardForm().getUserVipCardId() });
				List<YrUserVipCardRentForm> userVipCardRentForms = new ArrayList<YrUserVipCardRentForm>();
				for (YrUserVipCardRent userVipCardRent : qrUserVipCardRent.getResultList()) {
					userVipCardRentForms.add(ObjectUtils.objectToObject(userVipCardRent, YrUserVipCardRentForm.class));
				}
			}
		}
		sqlWhere = "elder_id=?1";
		QueryResult<YrCgIndiServiceSendOrder> qrCgIndiServiceSendOrder = cgIndiServiceSendOrderService
				.find(YrCgIndiServiceSendOrder.class, sqlWhere, new Object[] { form.getElderId() });
		if (qrCgIndiServiceSendOrder.getTotalRecord() > 0) {
			YrCgIndiServiceSendOrderForm cgIndiServiceSendOrderForm = ObjectUtils.objectToObject(
					qrCgIndiServiceSendOrder.getResultList().get(0), YrCgIndiServiceSendOrderForm.class);
			YrCaregiver caregiver = caregiverService.findOne(cgIndiServiceSendOrderForm.getCaregiverId());
			if (null != caregiver) {
				cgIndiServiceSendOrderForm
						.setCaregiverForm(ObjectUtils.objectToObject(caregiver, YrCaregiverForm.class));
			}
			form.setCgIndiServiceSendOrderForm(cgIndiServiceSendOrderForm);
		}
		QueryResult<YrCgSendOrder> qrCgSendOrder = cgSendOrderService.find(YrCgSendOrder.class, sqlWhere,
				new Object[] { form.getElderId() });
		if (qrCgSendOrder.getTotalRecord() > 0) {
			YrCgSendOrderForm cgSendOrderForm = ObjectUtils.objectToObject(qrCgSendOrder.getResultList().get(0),
					YrCgSendOrderForm.class);
			YrCaregiver caregiver = caregiverService.findOne(cgSendOrderForm.getCaregiverId());
			if (null != caregiver) {
				cgSendOrderForm.setCaregiverForm(ObjectUtils.objectToObject(caregiver, YrCaregiverForm.class));
			}
			form.setCgSendOrderForm(cgSendOrderForm);
		}
		if(form.getHouseTypeType()==2){//如果是普通户型
			YrBedCost bedCost = bedCostService.findOne(form.getBedCostId());
			if(null!=bedCost){
				YrBedCostForm bedCostForm = ObjectUtils.objectToObject(bedCost, YrBedCostForm.class);
				form.setBedCostForm(bedCostForm);
			}
		}
		YrBaseServiceCost baseServiceCost = baseServiceCostService.findOne(form.getBaseServiceCostId());
		if(null!=baseServiceCost){
			YrBaseServiceCostForm baseServiceCostForm = ObjectUtils.objectToObject(baseServiceCost, YrBaseServiceCostForm.class);
			form.setBaseServiceCostForm(baseServiceCostForm);
		}
		YrNursingCost nursingCost = nursingCostService.findOne(form.getNursingCostId());
		if(null!=nursingCost){
			YrNursingCostForm nursingCostForm = ObjectUtils.objectToObject(nursingCost, YrNursingCostForm.class);
			form.setNursingCostForm(nursingCostForm);
		}
		
		List<YrElderBeHospitalForm> formList = new ArrayList<YrElderBeHospitalForm>();
		YrStaffInfo staffInfo = staffInfoService.findOne(form.getCreateId());
		form.setCreator(staffInfo == null ? "" : staffInfo.getName());
		formList.add(form);

		result.setData(formList);
		return result;
	}

	@Override
	public YrElderBeHospitalForm toForm(YrElderBeHospital e) throws Exception {
		YrElderBeHospitalForm form = ObjectUtils.objectToObject(e, YrElderBeHospitalForm.class);
		return form;
	}

	@Override
	public YrElderBeHospital toEntity(YrElderBeHospitalForm f) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}
	
}
